package com.chalk.common.plugins.aliyun;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.chalk.common.util.GsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author xiaoqiang
 * @Description 短信验证 client
 * @date 2018/11/6 10:59
 */
@Component
public class AliSmsClient {

    private static final Logger LOGGER = LoggerFactory.getLogger(AliSmsClient.class);

    /* 产品名称:云通信短信API产品,开发者无需替换 */
    static final String product = "Dysmsapi";
    /* 产品域名,开发者无需替换 */
    static final String domain = "dysmsapi.aliyuncs.com";

    /* 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找) */
    private static String accessKeyId;

    private static String accessKeySecret;

    /* 签名 */
    private static String signName;

    /**
     * 发送短信验证码
     *
     * @param phone        手机号
     * @param code         验证码
     * @param templateCode 短信模板
     * @return
     * @throws ClientException
     */
    public static boolean sendSmsCode(String phone, String code, String templateCode) throws ClientException {
        LOGGER.info("短信验证码接口发送的数据：Phone = {}, Code = {}, SignName = {}, TemplateCode = {}", phone, code, signName, templateCode);
        /* 可自助调整超时时间 */
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        /* 初始化acsClient,暂不支持region化 */
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        /* 组装请求对象-具体描述见控制台-文档部分内容 */
        SendSmsRequest request = new SendSmsRequest();
        /* 必填:待发送手机号 */
        request.setPhoneNumbers(phone);
        /* 必填:短信签名-可在短信控制台中找到 */
        request.setSignName(signName);
        /* 必填:短信模板-可在短信控制台中找到 */
        request.setTemplateCode(templateCode);
        /* 可选:模板中的变量替换JSON串 */
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        /* 选填-上行短信扩展码(无特殊需求用户请忽略此字段) */
        //request.setSmsUpExtendCode("90997");
        /* 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 */
        //request.setOutId("100003844");
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        LOGGER.info("短信验证码接口返回的数据：Code = {}, Message = {}, RequestId = {}, BizId = {}", sendSmsResponse.getCode(), sendSmsResponse.getMessage(), sendSmsResponse.getRequestId(), sendSmsResponse.getBizId());
        String responseCode = sendSmsResponse.getCode();
        if ("OK".equals(responseCode)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送短信内容
     *
     * @param phone        手机号
     * @param content      内容
     * @param templateCode 短信模板
     * @return
     * @throws ClientException
     */
    public static boolean sendSmsContent(String phone, Map<String, String> content, String templateCode) throws ClientException {
        LOGGER.info("短信内容接口发送的数据：Phone = {}, Content = {}, SignName = {}, TemplateCode = {}", phone, GsonUtil.beanToJson(content), signName, templateCode);
        /* 可自助调整超时时间 */
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        /* 初始化acsClient,暂不支持region化 */
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        /* 组装请求对象-具体描述见控制台-文档部分内容 */
        SendSmsRequest request = new SendSmsRequest();
        /* 必填:待发送手机号 */
        request.setPhoneNumbers(phone);
        /* 必填:短信签名-可在短信控制台中找到 */
        request.setSignName(signName);
        /* 必填:短信模板-可在短信控制台中找到 */
        request.setTemplateCode(templateCode);
        /* 可选:模板中的变量替换JSON串 */
        request.setTemplateParam(GsonUtil.beanToJson(content));
        /* 选填-上行短信扩展码(无特殊需求用户请忽略此字段) */
        //request.setSmsUpExtendCode("90997");
        /* 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 */
        //request.setOutId("100003844");
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        LOGGER.info("短信内容接口返回的数据：Code = {}, Message = {}, RequestId = {}, BizId = {}", sendSmsResponse.getCode(), sendSmsResponse.getMessage(), sendSmsResponse.getRequestId(), sendSmsResponse.getBizId());
        String responseCode = sendSmsResponse.getCode();
        if (responseCode.equals("OK")) {
            return true;
        } else {
            return false;
        }
    }

    @Value("${aliyun.sms.access-key-id}")
    public void setAccessKeyId(String accessKeyId) {
        AliSmsClient.accessKeyId = accessKeyId;
    }

    @Value("${aliyun.sms.access-key-secret}")
    public void setAccessKeySecret(String accessKeySecret) {
        AliSmsClient.accessKeySecret = accessKeySecret;
    }

    @Value("${aliyun.sms.sign-name}")
    public void setSignName(String signName) {
        AliSmsClient.signName = signName;
    }

}
